package com.apexedu.sync.node.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.apexedu.biz.Const;
import com.apexedu.framework.dao.BaseDao;
import com.apexedu.framework.util.DBUtil;
import com.apexedu.framework.util.SeqFactory;
import com.apexedu.identity.entity.TSysRole;
import com.apexedu.identity.entity.TSysUser;
import com.apexedu.identity.entity.TSysUserRole;
import com.apexedu.portal.util.DBMUtil;
import com.apexedu.sync.contant.Constants;
import com.apexedu.sync.engine.ISyncContext;
import com.apexedu.sync.entity.SyncAppModelMsg;
import com.apexedu.sync.exception.AuCSyncException;
import com.apexedu.sync.node.ISyncNode;
import com.apexedu.sys.SysConstant;
import com.apexedu.sys.util.BusinessLogUtil;

/**
 * 同步用户角色关联关系
 * Created by ly on 2015/1/12.
 */
public class UserRoleNode extends BaseNode implements ISyncNode {
	@Override
	public void execute(ISyncContext context) throws AuCSyncException {
		DBMUtil dbmUtil = context.getDbmUtil(); //多数据源工具类
		BaseDao baseDao = context.getBaseDao();

		String msg;
		try {

			//旧的用户角色关系List
			List<TSysUserRole> oldUserRoleList = null;
			String sql_oldUserRoleList = "";
			sql_oldUserRoleList += " select * ";
			sql_oldUserRoleList += " from t_sys_user_role a";
			sql_oldUserRoleList += " where exists (select null from t_sys_role b where a.roleid=b.roleid and b.belongtoapp=?)";
			oldUserRoleList = DBUtil.queryAllBeanList(sql_oldUserRoleList, TSysUserRole.class, context.getAppid());

			//缓存的用户Map
			Map<String, TSysUser> cachedUserMap = context.getMapUser();
			/* 缓存的用户Map为空时进行初始化 */
			if (cachedUserMap.isEmpty()) {
				String sql_userMap = "select * from t_sys_user where state != 0";
				List<TSysUser> userList = DBUtil.queryAllBeanList(sql_userMap, TSysUser.class);
				for (TSysUser user : userList) {
					cachedUserMap.put(user.getUserloginid(), user);
				}
			}
			//缓存的角色Map
			Map<String, TSysRole> cachedRoleMap = context.getMapRole();

			//待添加用户角色关系map
			Map<String, TSysUserRole> needAddUserRoleMap = new HashMap<String, TSysUserRole>();
			//待添加用户角色关系list
			List<TSysUserRole> needAddUserRoleList = null;
			/*查询待添加用户角色关系list*/
			String sql_needAddUserRole = "";
			if (context.isLivebos()) { //livebos系统
				sql_needAddUserRole += " select h.userid as userid,t.roleid as roleid ";
				sql_needAddUserRole += " from lbmember t,tuser h ";
				sql_needAddUserRole += " where h.id=t.userid";
			} else if (context.isApexssh()) { //apexssh系统
				sql_needAddUserRole += " select b.userloginid as userid,a.roleid as roleid ";
				sql_needAddUserRole += " from t_sys_user_role a ";
				sql_needAddUserRole += " inner join t_sys_user b on a.userid=b.userid";
			}
			needAddUserRoleList = dbmUtil.queryAllBeanList(sql_needAddUserRole, TSysUserRole.class);
			
			/*迭代待添加用户角色关系list，如果对应的用户和角色同时存在，则符合条件，否则移除出list*/
			for (int i = 0; i < needAddUserRoleList.size(); i++) {
				TSysUserRole needAddUserRoleTemp = needAddUserRoleList.get(i);
				String needAddUserIdTemp = needAddUserRoleTemp.getUserid();
				String needAddRoleIdTemp = needAddUserRoleTemp.getRoleid();
				TSysUser cachedUserTemp = cachedUserMap.get(needAddUserIdTemp);
				TSysRole cachedRoleTemp = cachedRoleMap.get(needAddRoleIdTemp);
				if (null != cachedUserTemp && null != cachedRoleTemp) {//用户角色关系对应的用户和角色都存在,则往需要添加的用户角色关系Map中放入一条记录
					String newSeqValue = SeqFactory.getNewSequenceAlone();
					needAddUserRoleTemp.setId(newSeqValue);
					needAddUserRoleTemp.setUserid(cachedUserTemp.getUserid());
					needAddUserRoleTemp.setRoleid(cachedRoleTemp.getRoleid());
					String userRoleKey = getKey(needAddUserRoleTemp);
					needAddUserRoleMap.put(userRoleKey, needAddUserRoleTemp);
				} else { //不存在于用户表或角色表中，从用户角色关系List中移除
					needAddUserRoleList.remove(i);
					i--;
				}
			}

			/* 迭代旧的用户角色列表，检索出已存在的与需删除的 */
			//待删除用户角色关系List
			List<TSysUserRole> needRemoveUserRoleList = new ArrayList<TSysUserRole>();
			for (TSysUserRole oldUserRoleTemp : oldUserRoleList) {
				//用户角色key值（格式为:角色id-用户id）
				String oldUserRoleKeyTemp = getKey(oldUserRoleTemp);
				//从待添加的用户角色Map中取出指定key值的对象
				TSysUserRole needAddUserRoleTemp = needAddUserRoleMap.get(oldUserRoleKeyTemp);
				if (null == needAddUserRoleTemp) {//对象为null，说明该对象在最新的待添加用户角色列表中没有，表示这是一条已经过时的无效数据，加入到待删除list中
					needRemoveUserRoleList.add(oldUserRoleTemp);
				} else {//对象不为null，说明同时存在于旧的角色关系列表和待添加角色关系列表中，将其从待添加列表移除
					needAddUserRoleList.remove(needAddUserRoleTemp);
					needAddUserRoleMap.remove(oldUserRoleKeyTemp);
				}
			}

			//保存待新增用户角色关系List
			if (!needAddUserRoleList.isEmpty()) {
				baseDao.saveAll(needAddUserRoleList);
			}

			//删除待删除用户角色关系List
			if (!needRemoveUserRoleList.isEmpty()) {
				baseDao.deleteAll(needRemoveUserRoleList);
			}

			msg = "插入：" + needAddUserRoleList.size() + "条，删除：" + needRemoveUserRoleList.size() + "条";
			BusinessLogUtil.log(getUserInfo(context), SysConstant.CZDX_T_SYS_USER_ROEL, Const.LOG_ACTION_UPDATE, "", msg);
			context.getMsg().getListModelMsg().add(new SyncAppModelMsg(Constants.NodeType.USER_ROLE, msg));
		} catch (Exception e) {
			e.printStackTrace();
			msg = e.getMessage();
			log.error("UserRoleNode error : " + msg);
			context.getMsg().getListModelMsg().add(new SyncAppModelMsg(Constants.NodeType.USER_ROLE, msg));
			throw new AuCSyncException(AuCSyncException.UNKNOWN_SERVICE_ERROR, msg);
		}
	}

	/**
	 * 获取用户角色关系集合的key值
	 *
	 * @param userRole 用户角色关系
	 * @return
	 */
	private String getKey(TSysUserRole userRole) {
		return userRole.getRoleid() + "-" + userRole.getUserid();
	}
}
